#include <WiFiManager.h>
#include <Sim800L.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define SIM_RX 2
#define SIM_TX 0

Sim800L sim800l(SIM_RX, SIM_TX);  // 创建 SIM800L 实例
String serverURL = "http://110.40.34.40:9011/receive_sms.php";

void setup() {
  Serial.begin(9600);
  initWifi();
  initSim800L();
}

void loop() {
  checkAndForwardSMS();
  delay(1000);  // 等待一段时间以避免循环过快
}

/**
 * 初始化 WiFi 连接
 */
void initWifi() {
  WiFiManager wifiManager;
  if (!wifiManager.autoConnect("SIM800L_Forwarder", "12345678")) {
    Serial.println("WiFi connection failed, restarting...");
    ESP.restart();
  }
  Serial.println("Connected to WiFi. IP address: " + WiFi.localIP().toString());
}

/**
 * 初始化 SIM800L 模块
 */
void initSim800L() {
  sim800l.begin(4800);  // 启动 SIM800L，波特率为 4800
  bool ready = false;

  // 重试多次以等待 SIM800L 准备就绪
  for (int i = 0; i < 30; i++) {
    if (sim800l.prepareForSmsReceive()) {
      Serial.println("SIM800L is ready.");
      ready = true;
      break;
    }
    Serial.println("Waiting for SIM800L to be ready...");
    delay(1000);
  }

  if (!ready) {
    Serial.println("SIM800L initialization failed, restarting...");
    ESP.restart();
  }
}

/**
 * 检查并转发接收到的短信
 */
void checkAndForwardSMS() {
  byte index = sim800l.checkForSMS();
  if (index > 0) {  // 如果有新短信
    String smsContent = sim800l.readSms(index);
    Serial.println("Received SMS: " + smsContent);
    sendSMSContentToServer(smsContent);
  }
}

/**
 * 将短信内容发送到服务器
 */
bool sendSMSContentToServer(String content) {
  WiFiClient client;
  HTTPClient http;

  http.begin(client, serverURL);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  String data = "content=" + content;
  int responseCode = http.POST(data);

  if (responseCode > 0) {
    String response = http.getString();
    Serial.println("Server response: " + response);
  } else {
    Serial.print("Failed to send POST request. Error code: ");
    Serial.println(responseCode);
  }

  http.end();
  return responseCode > 0;
}
